import sys,gzip,glob
from multiprocessing import Pool

def get_q30(infile, inputdir):
    sampleid = infile.strip().split('/')[-1].split('.')[0]
    fastq_file = gzip.open(infile, 'rt', encoding='utf-8')
    count = 0
    q30 = 0
    all = 0
    for line in fastq_file:
        count += 1
        fastq_file.readline()
        fastq_file.readline()
        l = fastq_file.readline().strip()
        all += len(l)
        read_n = 0
        read_sum = 0
        for each in l:
            qual = ord(each) - 33
            if qual >= 30: 
                q30 += 1
                read_n += 1
            read_sum += 1
        if read_n / read_sum < 0.8:
            q30 -= read_n
            all -= read_sum
            continue
        if count > 10_000_000:
            break
    q30_count = str('%.2f' % (q30/all * 100))
    with open(f'{inputdir}/{sampleid}.q30', 'w') as out:
        out.write(sampleid + '\t' + q30_count + '\n')

if __name__ == "__main__":
    p = Pool(18)
    inputdir = sys.argv[1]
    files = glob.glob(f'{inputdir}/*.gz')
    for i in files:
        if i.find('Undetermined') > -1:
            continue
        p.apply_async(get_q30,(i,inputdir))

    p.close()
    p.join()
